<template>
  <div class="navbar">
    <div class="logo">
      <router-link to="/">技术问答与在线互助论坛系统</router-link>
    </div>
    <div class="nav-links">
      <button class="ask-btn" v-if="isLoggedIn" @click="goToAskPost">
        提问
      </button>
    </div>
    <div class="user-section">
      <button class="feedback-btn" v-if="isLoggedIn" @click="goToFeedback">
        反馈
      </button>
      <div class="user-dropdown" @click.stop="toggleDropdown" ref="dropdown">
        <img :src="userAvatar" alt="用户头像" class="avatar" v-if="isLoggedIn" @error="handleAvatarError">
        <span class="username" v-if="isLoggedIn">{{ userName }}</span>
        <span class="login-btn" v-else @click="goToLogin">登录/注册</span>
        <transition name="fade">
          <div class="dropdown-menu" v-show="showDropdown" @click.stop>
            <div class="dropdown-item" @click="goToProfile">
              <el-icon>
                <User />
              </el-icon> 个人中心
            </div>
            <div class="dropdown-item" @click="logout">
              <el-icon>
                <SwitchButton />
              </el-icon> 退出登录
            </div>
          </div>
        </transition>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { useRouter } from 'vue-router'
import { getToken, removeToken } from '@/utils/cookie'
import { getUserInfoService } from '@/apis/user'
import defaultAvatar from '@/assets/images/default-avatar.png'
import { User, ChatDotRound, SwitchButton, QuestionFilled } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { logoutService } from '@/apis/user'

export default {
  name: 'NavBar',
  components: { User, ChatDotRound, SwitchButton },
  setup() {
    const router = useRouter()
    const dropdown = ref(null)
    const showDropdown = ref(false)
    const isLoggedIn = ref(!!getToken())
    const userName = ref('')
    const userId = ref('')
    const userAvatar = ref(defaultAvatar)

    const checkLoginStatus = async () => {
      isLoggedIn.value = !!getToken()
      if (isLoggedIn.value) {
        await fetchUserInfo()
      }
    }

    const fetchUserInfo = async () => {
      try {
        const res = await getUserInfoService(userId)
        if (res.code === 1000) {
          userName.value = res.data.nickName || '用户'
          userId.value = res.data.userId
          userAvatar.value = res.data.profilePicture
        } else {
          throw new Error(res.msg || '获取用户信息失败')
        }
      } catch (error) {
        console.error('获取用户信息失败:', error)
        ElMessage.error(error.message)
      }
    }

    const handleAvatarError = (e) => {
      e.target.src = defaultAvatar
    }

    const toggleDropdown = () => {
      showDropdown.value = !showDropdown.value
    }

    const handleClickOutside = (event) => {
      if (dropdown.value && !dropdown.value.contains(event.target)) {
        showDropdown.value = false
      }
    }

    const goToLogin = () => router.push('/forum/login')
    const goToProfile = () => {
      router.push({
        path: '/forum/profile',
        query: { userId: userId.value }
      })
      showDropdown.value = false
    }
    const goToAskPost = () => {
      router.push('/forum/ask')  // 修改此行
      showDropdown.value = false
    }
    
    const goToFeedback = () => {
      router.push('/forum/feedback')
      showDropdown.value = false
    }
    const logout = async () => {
      await ElMessageBox.confirm(
        '确认退出',
        '温馨提示',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        }
      )
      await logoutService()
      removeToken()
      isLoggedIn.value = false
      showDropdown.value = false
      router.push('/forum/login')
    }

    onMounted(() => {
      checkLoginStatus()
      document.addEventListener('click', handleClickOutside)
    })

    onBeforeUnmount(() => {
      document.removeEventListener('click', handleClickOutside)
    })

    return {
      dropdown,
      showDropdown,
      isLoggedIn,
      userName,
      userAvatar,
      toggleDropdown,
      goToLogin,
      goToProfile,
      goToFeedback,
      goToAskPost,
      logout,
      handleAvatarError
    }
  }
}
</script>

<style scoped>
.navbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 24px;
  background-color: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  position: sticky;
  top: 0;
  z-index: 1000;
}

.logo a {
  font-size: 20px;
  font-weight: bold;
  color: #333;
  text-decoration: none;
}

.nav-links {
  display: flex;
  gap: 8px;
  margin-left: auto;
  margin-right: 16px;
}

.ask-btn {
  padding: 8px 16px;
  border-radius: 20px;
  color: white;
  background: linear-gradient(90deg, #1890ff, #36c6d9);
  border: none;
  box-shadow: 0 2px 8px rgba(24, 144, 255, 0.3);
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 6px;
}

.ask-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(24, 144, 255, 0.4);
}

.nav-link {
  color: #666;
  text-decoration: none;
  padding: 8px 16px;
  border-radius: 6px;
  font-size: 15px;
  transition: all 0.2s ease;
}

.nav-link:hover {
  color: #1890ff;
}

.nav-link.active {
  color: #1890ff;
  background-color: #e6f7ff;
}

.user-section {
  position: relative;
}

.user-dropdown {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  padding: 8px 12px;
  border-radius: 6px;
  transition: all 0.2s ease;
}

.user-dropdown:hover {
  background-color: #f5f5f5;
}

.avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  object-fit: cover;
  border: 1px solid #f0f0f0;
}

.username {
  font-size: 14px;
  font-weight: 500;
}

.login-btn {
  cursor: pointer;
  color: #1890ff;
  font-weight: 500;
  padding: 8px 16px;
}

.dropdown-menu {
  position: absolute;
  right: 0;
  top: 100%;
  background-color: #fff;
  border: 1px solid #f0f0f0;
  border-radius: 6px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  z-index: 100;
  min-width: 180px;
  margin-top: 8px;
}

.dropdown-item {
  padding: 10px 16px;
  font-size: 14px;
  color: #333;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  gap: 8px;
}

.dropdown-item:hover {
  background-color: #f5f5f5;
  color: #1890ff;
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.2s, transform 0.2s;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
  transform: translateY(-10px);
}
</style>

<style scoped>
.user-section {
  display: flex;
  align-items: center;
  gap: 8px;
}

.feedback-btn {
  padding: 8px 16px;
  border-radius: 20px;
  color: white;
  background: linear-gradient(90deg, #36c6d9, #1890ff);
  border: none;
  box-shadow: 0 2px 8px rgba(54, 198, 217, 0.3);
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 15px;
}

.feedback-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(54, 198, 217, 0.4);
}
</style>